package com.ruoyi.project.wenyanwen.generate.convert;

import com.ruoyi.common.utils.JsonUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.project.wenyanwen.generate.domain.mysql.MysqlZi;
import com.ruoyi.project.wenyanwen.generate.domain.sqlite.KangxiSqlite;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@Component
public class KangxiConvert extends AbstractConvert {

    protected static Log logger = LogFactory.getLog(KangxiConvert.class);

    @Autowired
    @Qualifier("ssdbTemplate")
    RedisTemplate<String, String> redisTemplate;

    public static List<Map> RULE = null;

    public String replace(String s) {

        if (RULE == null) {
            String rule = redisTemplate.opsForValue().get("rule");
            RULE = JsonUtil.toListObject(rule, Map.class);
        }

        s = s.replace("\n", "").replace("\r", "");

        logger.debug(s);

        for (Map map : RULE) {
            String c = map.get("c").toString();
            String r = map.get("r").toString();
            s = s.replace(r, c);
        }
        return s;
    }

    @Override
    public List<KangxiSqlite> convert(List<?> list) {

        List<KangxiSqlite> l = new ArrayList<>();

        for (Object obj : list) {

            MysqlZi zi = (MysqlZi) obj;
            KangxiSqlite model = new KangxiSqlite();
            model.setId(zi.getId().intValue());
            model.setZi(zi.getZiString());
            String kxzd = (String) redisTemplate.opsForHash().get("kxzd", zi.getZiString());
            if (StringUtils.isEmpty(kxzd)) {
                continue;
            }
            int beforeSize = kxzd.length();
            kxzd = replace(kxzd);
            int afterSize = kxzd.length();
            logger.info("beforeSize[" + beforeSize + "], afterSize[" + afterSize + "]");
            model.setZhujie(zipAndencrypt(kxzd));
            l.add(model);
        }

        return l;
    }
}
